""" 
功能:
图片浏览器

前置教程:
16_pyqt5_resize_setGeometry_画面布局_元素大小_固定位置_比例缩放_设置.py
21_pyqt5_显示图片.py
21.1_pyqt5_缩放图片_适应程序大小.py
25_pyqt5_按键捕获.py

"""

import sys
import os
import glob
import subprocess
from PyQt5 import QtWidgets
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
from picture import *

picture_type = [".jpg", ".png", ".jpeg", ".bmp", ".gif"]
ui_size = {
    "360p": (640, 360),
    "480p": (854, 480),
    "720p": (1280, 720),
    "1080p": (1920, 1080),
}


class Ui_Picture(Ui_Form):
    def __init__(self, form):
        super().__init__()
        self.widgets = form
        self.setupUi(form)
        self.callback_init()
        self.picture_index = 0
        self.picture_list = []
        # 设置焦点为widgets
        self.widgets.setFocusPolicy(Qt.StrongFocus)

    def callback_init(self):
        self.btn_choose_dir.clicked.connect(self.choose_picture_dir)

    def choose_picture_dir(self):
        folder_path = QtWidgets.QFileDialog.getExistingDirectory(
            self.widgets, "选择文件夹", os.getcwd()
        )
        picture_list = []
        # picture_list += glob.glob(f"{folder_path}/*.jpg")
        # picture_list += glob.glob(f"{folder_path}/*.png")
        for type in picture_type:
            picture_list += glob.glob(f"{folder_path}/*{type}")

        self.picture_list = sorted(picture_list)
        self.text_picture_info.clear()
        self.text_picture_info.append("\n".join(self.picture_list))
        self.show_picture(self.picture_list[self.picture_index])

    def show_picture(self, path):
        pixmap = QPixmap(path)
        # 获取图片的原始尺寸
        original_width = pixmap.width()
        original_height = pixmap.height()
        # 获取窗口的尺寸
        window_width = self.widgets.width()
        window_height = self.widgets.height()
        # 计算缩放比例
        scale_width = window_width / original_width
        scale_height = window_height / original_height
        # 选择较小的缩放比例，确保图片完整显示在窗口内
        scale = min(scale_width, scale_height)
        # 缩放图片
        scaled_pixmap = pixmap.scaled(
            int(original_width * scale), int(original_height * scale)
        )
        self.label_picture.setPixmap(scaled_pixmap)
        self.label_picture.setAlignment(Qt.AlignCenter)

    def keyPressEvent(self, event):
        # 当按下按键时触发此事件处理函数
        if event.key() == Qt.Key_Left:
            print("Left key pressed")
            if self.picture_index == 0:
                self.text_picture_info.append("this is first picture")
                return
            self.picture_index -= 1
            self.show_picture(self.picture_list[self.picture_index])

        elif event.key() == Qt.Key_Right:
            print("Right key pressed")
            if self.picture_index == len(self.picture_list) - 1:
                self.text_picture_info.append("this is end picture")
                return
            self.picture_index += 1
            self.show_picture(self.picture_list[self.picture_index])

        elif event.key() in (Qt.Key_1, Qt.Key_2, Qt.Key_3, Qt.Key_4):
            self.adjust_ui_layout(event.key)

        print(f"其他键被按下: {event.text()}, 键码: {event.key()}")

    def adjust_ui_layout(self, key):
        global ui_size
        if key() == Qt.Key_1:
            width, height = ui_size["360p"]
        elif key() == Qt.Key_2:
            width, height = ui_size["480p"]
        elif key() == Qt.Key_3:
            width, height = ui_size["720p"]
        elif key() == Qt.Key_4:
            width, height = ui_size["1080p"]
        self.label_picture.setGeometry(0, 0, width, height)
        self.widgets.resize(width, height+100)

        self.horizontalLayoutWidget.setGeometry(
            QtCore.QRect(0, height, int(width / 2), 100)
        )
        self.text_picture_info.setGeometry(
            QtCore.QRect(int(width / 2), height, int(width / 2), 100)
        )
        self.show_picture(self.picture_list[self.picture_index])

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Picture(Form)
    Form.show()
    Form.keyPressEvent = ui.keyPressEvent  # 将 keyPressEvent 绑定到 Form 上
    sys.exit(app.exec_())
